<!--
 * @Author: 颜礼田 2564217790@qq.com
 * @Date: 2024-08-26 17:47:16
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-25 21:55:03
 * @FilePath: /turo-repo-enterprise/apps/fuck-enterprise-admin/src/views/system/permission/components/edit.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-drawer v-model="visible" title="角色编辑">
    <el-form ref="formRef" :model="modelValue" :rules="rules" label-position="top">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="modelValue.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色编码" prop="roleCode">
        <el-input v-model="modelValue.roleCode"></el-input>
      </el-form-item>
      <el-form-item label="角色可访问菜单列表" prop="menus">
        <div class="tree">
          <el-tree
            ref="treeRef"
            v-model="modelValue.menus"
            style="max-width: 100%"
            :data="options"
            show-checkbox
            default-expand-all
            node-key="id"
            :props="props"
          />
        </div>
      </el-form-item>
      <el-form-item label="角色权限列表" prop="permission">
        <el-descriptions style="width: 100%" :column="1" border>
          <template #extra>
            <el-button @click="openPermission" type="primary">添加</el-button>
          </template>
          <el-descriptions-item v-for="item of modelValue.permission" :key="item.id" :label="item?.permissionCode">
            {{ item?.permissionName ?? "--" }}
          </el-descriptions-item>
        </el-descriptions>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button @click="submit" type="primary">确定</el-button>
    </template>
    <Permission ref="permissionRef" @success="selectedPermission"></Permission>
  </el-drawer>
</template>

<script lang="ts" setup>
import { Role, saveRole, fetchRoleInfo, editRole } from "@/api/modules/roles";
import { ResultEnum } from "@/enums/httpEnum";
import { ElNotification, FormInstance } from "element-plus";
import { reactive } from "vue";
import { ref } from "vue";
import { useAuthStore } from "@/stores/modules/auth";

import Permission from "./permission.vue";
import { storeToRefs } from "pinia";
import { EmitProps } from "@/typings/interface";
import { nextTick } from "vue";
import { isNotEmpty } from "@/utils/isHelper";
import { watch } from "vue";

const visible = ref<boolean>(false);

const props = { label: "title", children: "children" };
const { authMenuList } = storeToRefs(useAuthStore());
const options = ref(authMenuList.value);

const permissionRef = ref<HTMLOptionOpenElement>();
function openPermission() {
  permissionRef.value?.open(modelValue.permission);
}

function selectedPermission(selectedList) {
  modelValue.permission = selectedList;
}

const modelValue = reactive<Role>({
  roleName: "",
  permission: [],
  menus: [],
  roleCode: ""
});

const rules = {
  roleCode: [{ required: true, trigger: "blur", message: "请输入角色编码" }],
  roleName: [{ required: true, trigger: "blur", message: "请输入角色名称" }]
};

const treeRef = ref();
const formRef = ref<FormInstance>();
const emit = defineEmits<EmitProps>();

function submit() {
  modelValue.menus = treeRef.value.getCheckedNodes();
  formRef.value?.validate().then(valid => {
    if (valid) {
      if (isNotEmpty(modelValue.id)) {
        edit();
      } else {
        save();
      }
    }
  });
}

function edit() {
  editRole({ id: modelValue?.id }, modelValue).then(r => {
    const { code, message } = r;
    if (code === ResultEnum.SUCCESS) {
      visible.value = false;
      emit("success");
      ElNotification.success("编辑成功！");
    } else {
      ElNotification.error(message);
    }
  });
}

function save() {
  saveRole(modelValue).then(r => {
    const { code, message } = r;
    if (code === ResultEnum.SUCCESS) {
      visible.value = false;
      emit("success");
      ElNotification.success("添加成功！");
    } else {
      ElNotification.error(message);
    }
  });
}

defineExpose({
  open(row) {
    visible.value = true;
    if (isNotEmpty(row) && isNotEmpty(row.id)) {
      fetchRoleInfo({ id: row.id }).then(r => {
        const { code, data, message } = r;
        if (code == ResultEnum.SUCCESS) {
          nextTick(() => {
            Object.assign(modelValue, data);
            // 如果组件不存在，且存在重定义地址，那么这个菜单就是父级菜单
            treeRef.value?.setCheckedNodes(
              data.menus.filter(ele => isNotEmpty(ele.component) && !isNotEmpty(ele.redirect)),
              true
            );
          });
        } else {
          ElNotification.error(message);
        }
      });
    }
  }
});

watch(
  () => visible.value,
  newVal => {
    if (!newVal) {
      formRef.value?.resetFields();
      treeRef.value?.setCheckedNodes([]);
      if (isNotEmpty(modelValue.menus)) {
        modelValue.menus = [];
      }
      modelValue.id = "";
    }
  }
);
</script>

<style lang="scss" scoped>
.tree {
  width: 100%;
  height: 180px;
  padding: 4px;
  overflow-y: auto;
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
}
</style>
